// 创建头部组件
function createHeader() {
    const headerHTML = `
        <!-- 顶部导航栏 -->
        <div class="layui-row header-container">
            <div class="top-bar-header">
                <div class="top-bar-header-a" id="loginStatus">请<a class="login" href="./register.html">注册</a>/<a class="login" href="./login.html">登录</a>账号</div>
                <div class="top-bar-header-a car" id="toCartPage">购物车</div>
                <div class="top-bar-header-a" id="toOrderPage">我的订单</div>
            </div>
        </div>

        <!-- 主导航栏 -->
        <div class="layui-col-xs12 layui-col-sm12 layui-col-md12 main-nav">
            <div class="center">
                <div class="grid-demo">
                    <div class="containerHeader">
                        <div class="containerHeaderMenu">
                            <div style="cursor:pointer"><img class="logo" src="./img/logo4.jpg" alt="logo" id="logoImg"></div>
                        </div>
                        <div class="containerHeaderMenu">
                            <div class="search-input-wrapper">
                                <input type="text"
                                    id="searchInput"
                                    placeholder="请输入书名、作者或关键词"
                                    autocomplete="off">
                                <button class="search-btn" id="searchBtn">
                                    <i class="fas fa-search"></i>
                                    <span>搜索</span>
                                </button>
                            </div>
                        </div>
                        <div class="containerHeaderMenu">
                            <button class="nav-btn cart-btn" id="toCart">
                                <i class="fas fa-shopping-cart"></i>
                                <span class="cart-btn">购物车</span>
                                <span class="badge" id="cartCount">0</span>
                            </button>
                            <button class="nav-btn order-btn" id="toOrder">
                                <i class="fas fa-list-ul"></i>
                                <span>我的订单</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    const headerContainer = document.getElementById('commonHeader');
    if (headerContainer) {
        headerContainer.innerHTML = headerHTML;
    }
}

// 页面加载时创建头部
document.addEventListener('DOMContentLoaded', function() {
    createHeader();
    // 如果header.js中的updateHeaderUI函数存在，则调用它
    if (typeof updateHeaderUI === 'function') {
        updateHeaderUI();
    }
});

// 通用头部逻辑
function updateHeaderUI() {
    // 检查登录状态并更新UI
    function updateLoginStatus() {
        // 使用AuthService更新登录状态UI
        if (window.AuthService) {
            AuthService.updateLoginUI();
        } else {
            // 兼容旧代码，如果AuthService不存在
            const username = localStorage.getItem('username');
            const loginStatusElement = document.getElementById('loginStatus');
            
            if (loginStatusElement) {
                if (username) {
                    loginStatusElement.innerHTML = `欢迎，<span class="username">${username}</span> | <a href="javascript:;" id="logoutBtn">退出</a>`;
                    
                    // 添加退出登录事件
                    const logoutBtn = document.getElementById('logoutBtn');
                    if (logoutBtn) {
                        logoutBtn.addEventListener('click', function() {
                            localStorage.removeItem('token');
                            localStorage.removeItem('username');
                            localStorage.removeItem('userId');
                            window.location.reload();
                        });
                    }
                } else {
                    loginStatusElement.innerHTML = '请<a class="login" href="./register.html">注册</a>/<a class="login" href="./login.html">登录</a>账号';
                }
            }
        }
    }
    
    // 更新购物车数量
    function updateCartCount() {
        // 使用AuthService更新购物车数量
        if (window.AuthService) {
            AuthService.updateCartCount();
        } else {
            // 兼容旧代码
            const token = localStorage.getItem('token');
            const cartCountElement = document.getElementById('cartCount');
            
            if (token && cartCountElement && window.ApiService) {
                ApiService.cart.getCart()
                    .then(response => {
                        const cartItems = response.data.items || [];
                        const count = cartItems.length;
                        cartCountElement.textContent = count;
                    })
                    .catch(error => {
                        console.error('获取购物车失败:', error);
                    });
            }
        }
    }
    
    // 绑定导航事件
    function bindNavigationEvents() {
        // Logo点击返回首页
        const logoImg = document.getElementById('logoImg');
        if (logoImg) {
            logoImg.addEventListener('click', function() {
                window.location.href = './home.html';
            });
        }
        
        // 搜索按钮
        const searchBtn = document.getElementById('searchBtn');
        if (searchBtn) {
            searchBtn.addEventListener('click', function() {
                const keyword = document.getElementById('searchInput').value.trim();
                window.location.href = `./catalog.html?keyword=${encodeURIComponent(keyword)}`;
            });
        }
        
        // 搜索框回车事件
        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    const keyword = this.value.trim();
                    if (keyword) {
                        window.location.href = `./catalog.html?keyword=${encodeURIComponent(keyword)}`;
                    }
                }
            });
        }
        
        // 购物车按钮
        const cartButtons = document.querySelectorAll('#toCart, #toCartPage');
        cartButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                // 使用AuthService检查登录状态
                if (window.AuthService) {
                    AuthService.checkLoginBeforeAction(() => {
                        window.location.href = './cart.html';
                    });
                } else {
                    // 兼容旧代码
                    if (localStorage.getItem('token')) {
                        window.location.href = './cart.html';
                    } else {
                        showLoginModal();
                    }
                }
            });
        });
        
        // 订单按钮
        const orderButtons = document.querySelectorAll('#toOrder, #toOrderPage');
        orderButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                // 使用AuthService检查登录状态
                if (window.AuthService) {
                    AuthService.checkLoginBeforeAction(() => {
                        window.location.href = './order.html';
                    });
                } else {
                    // 兼容旧代码
                    if (localStorage.getItem('token')) {
                        window.location.href = './order.html';
                    } else {
                        showLoginModal();
                    }
                }
            });
        });
        
        // 登录弹窗关闭按钮
        const closeBtn = document.getElementById('closeMask');
        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                const mask = document.getElementById('mask');
                if (mask) {
                    mask.style.display = 'none';
                }
            });
        }
    }
    
    // 显示登录弹窗
    function showLoginModal() {
        if (window.AuthService) {
            AuthService.showLoginModal();
        } else {
            const mask = document.getElementById('mask');
            if (mask) {
                mask.style.display = 'flex';
            } else {
                alert('请先登录');
                window.location.href = './login.html';
            }
        }
    }
    
    // 初始化
    updateLoginStatus();
    updateCartCount();
    bindNavigationEvents();
    const searchInput = document.getElementById('searchInput');
    searchInput.value = new URLSearchParams(window.location.search).get('keyword') || '';
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', updateHeaderUI);

// 导出函数以便其他脚本调用
window.updateHeaderUI = updateHeaderUI;